import { defineStore } from 'pinia';
import { ref, reactive } from 'vue';
import { Message } from '@arco-design/web-vue';
import logisticsApi from '@/api/logistics';

export const useLogisticsStore = defineStore('logistics', () => {
  // 状态
  const loading = ref(false);
  const companies = ref([]);
  const companyDetail = ref(null);
  const orders = ref([]);
  const orderDetail = ref(null);
  const trackingInfo = ref(null);
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const orderPagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0
  });

  /**
   * 获取物流公司列表
   * @param {Object} params - 查询参数
   * @param {Boolean} showLoading - 是否显示加载状态，默认为true
   * @returns {Promise} 请求结果
   */
  async function getLogisticsCompanyList(params = {}, showLoading = true) {
    if (showLoading) loading.value = true;
    
    try {
      const queryParams = {
        page: pagination.current,
        page_size: pagination.pageSize,
        ...params
      };
      
      const response = await logisticsApi.getLogisticsCompanyList(queryParams);
      
      if (response.code === 0) {
        companies.value = response.data.list || [];
        pagination.total = response.data.total || 0;
        Message.success('获取物流公司列表成功');
        return { success: true, data: companies.value };
      }
      
      Message.error(response.message || '获取物流公司列表失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('获取物流公司列表出错:', error);
      Message.error('获取物流公司列表失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      if (showLoading) loading.value = false;
    }
  }

  /**
   * 获取物流公司详情
   * @param {Number} id - 物流公司ID
   * @returns {Promise} 请求结果
   */
  async function getLogisticsCompanyDetail(id) {
    loading.value = true;
    try {
      const response = await logisticsApi.getLogisticsCompanyDetail(id);
      
      if (response.code === 0) {
        companyDetail.value = response.data;
        return { success: true, data: companyDetail.value };
      }
      
      Message.error(response.message || '获取物流公司详情失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('获取物流公司详情出错:', error);
      Message.error('获取物流公司详情失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 创建物流公司
   * @param {Object} data - 物流公司数据
   * @returns {Promise} 请求结果
   */
  async function createLogisticsCompany(data) {
    loading.value = true;
    try {
      const response = await logisticsApi.createLogisticsCompany(data);
      
      if (response.code === 0) {
        Message.success('创建物流公司成功');
        return { success: true };
      }
      
      Message.error(response.message || '创建物流公司失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('创建物流公司出错:', error);
      Message.error('创建物流公司失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 更新物流公司
   * @param {Number} id - 物流公司ID
   * @param {Object} data - 物流公司数据
   * @returns {Promise} 请求结果
   */
  async function updateLogisticsCompany(id, data) {
    loading.value = true;
    try {
      const response = await logisticsApi.updateLogisticsCompany(id, data);
      
      if (response.code === 0) {
        Message.success('更新物流公司成功');
        return { success: true };
      }
      
      Message.error(response.message || '更新物流公司失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('更新物流公司出错:', error);
      Message.error('更新物流公司失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 删除物流公司
   * @param {Number} id - 物流公司ID
   * @returns {Promise} 请求结果
   */
  async function deleteLogisticsCompany(id) {
    loading.value = true;
    try {
      const response = await logisticsApi.deleteLogisticsCompany(id);
      
      if (response.code === 0) {
        Message.success('删除物流公司成功');
        return { success: true };
      }
      
      Message.error(response.message || '删除物流公司失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('删除物流公司出错:', error);
      Message.error('删除物流公司失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 获取物流订单列表
   * @param {Object} params - 查询参数
   * @param {Boolean} showLoading - 是否显示加载状态，默认为true
   * @returns {Promise} 请求结果
   */
  async function getLogisticsOrderList(params = {}, showLoading = true) {
    if (showLoading) loading.value = true;
    
    try {
      const queryParams = {
        page: orderPagination.current,
        page_size: orderPagination.pageSize,
        ...params
      };
      
      const response = await logisticsApi.getLogisticsOrderList(queryParams);
      
      if (response.code === 0) {
        orders.value = response.data.list || [];
        orderPagination.total = response.data.total || 0;
        return { success: true, data: orders.value };
      }
      
      Message.error(response.message || '获取物流订单列表失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('获取物流订单列表出错:', error);
      Message.error('获取物流订单列表失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      if (showLoading) loading.value = false;
    }
  }

  /**
   * 获取物流订单详情
   * @param {Number} id - 物流订单ID
   * @returns {Promise} 请求结果
   */
  async function getLogisticsOrderDetail(id) {
    loading.value = true;
    try {
      const response = await logisticsApi.getLogisticsOrderDetail(id);
      
      if (response.code === 0) {
        orderDetail.value = response.data;
        return { success: true, data: orderDetail.value };
      }
      
      Message.error(response.message || '获取物流订单详情失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('获取物流订单详情出错:', error);
      Message.error('获取物流订单详情失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 创建物流订单
   * @param {Object} data - 物流订单数据
   * @returns {Promise} 请求结果
   */
  async function createLogisticsOrder(data) {
    loading.value = true;
    try {
      const response = await logisticsApi.createLogisticsOrder(data);
      
      if (response.code === 0) {
        Message.success('创建物流订单成功');
        return { success: true, data: response.data };
      }
      
      Message.error(response.message || '创建物流订单失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('创建物流订单出错:', error);
      Message.error('创建物流订单失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 更新物流订单
   * @param {Number} id - 物流订单ID
   * @param {Object} data - 物流订单数据
   * @returns {Promise} 请求结果
   */
  async function updateLogisticsOrder(id, data) {
    loading.value = true;
    try {
      const response = await logisticsApi.updateLogisticsOrder(id, data);
      
      if (response.code === 0) {
        Message.success('更新物流订单成功');
        return { success: true };
      }
      
      Message.error(response.message || '更新物流订单失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('更新物流订单出错:', error);
      Message.error('更新物流订单失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 删除物流订单
   * @param {Number} id - 物流订单ID
   * @returns {Promise} 请求结果
   */
  async function deleteLogisticsOrder(id) {
    loading.value = true;
    try {
      const response = await logisticsApi.deleteLogisticsOrder(id);
      
      if (response.code === 0) {
        Message.success('删除物流订单成功');
        return { success: true };
      }
      
      Message.error(response.message || '删除物流订单失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('删除物流订单出错:', error);
      Message.error('删除物流订单失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 查询物流信息
   * @param {String} trackingNumber - 物流单号
   * @param {String} company - 物流公司代码
   * @returns {Promise} 请求结果
   */
  async function trackLogistics(trackingNumber, company) {
    loading.value = true;
    try {
      const response = await logisticsApi.trackLogistics(trackingNumber, company);
      
      if (response.code === 0) {
        trackingInfo.value = response.data;
        return { success: true, data: trackingInfo.value };
      }
      
      Message.error(response.message || '查询物流信息失败');
      return { success: false, message: response.message };
    } catch (error) {
      console.error('查询物流信息出错:', error);
      Message.error('查询物流信息失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 打印物流单
   * @param {Number} id - 物流订单ID
   * @returns {Promise} 请求结果
   */
  async function printLogisticsOrder(id) {
    loading.value = true;
    try {
      const response = await logisticsApi.printLogisticsOrder(id);
      
      // 处理文件下载
      const blob = new Blob([response], { type: 'application/pdf' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `物流单-${id}.pdf`;
      link.click();
      URL.revokeObjectURL(link.href);
      
      Message.success('打印物流单成功');
      return { success: true };
    } catch (error) {
      console.error('打印物流单出错:', error);
      Message.error('打印物流单失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 设置公司分页
   * @param {Number} page - 页码
   * @param {Number} pageSize - 每页数量
   */
  function setCompanyPagination(page, pageSize) {
    pagination.current = page;
    if (pageSize) pagination.pageSize = pageSize;
  }

  /**
   * 设置订单分页
   * @param {Number} page - 页码
   * @param {Number} pageSize - 每页数量
   */
  function setOrderPagination(page, pageSize) {
    orderPagination.current = page;
    if (pageSize) orderPagination.pageSize = pageSize;
  }

  /**
   * 获取所有物流公司（用于下拉选择）
   * @returns {Promise} 请求结果
   */
  async function getAllLogisticsCompanies() {
    try {
      const response = await logisticsApi.getLogisticsCompanyList({ page_size: 9999 });
      
      if (response.code === 0) {
        return { success: true, data: response.data.list || [] };
      }
      
      return { success: false, message: response.message, data: [] };
    } catch (error) {
      console.error('获取所有物流公司出错:', error);
      return { success: false, message: error.message || '未知错误', data: [] };
    }
  }

  return {
    loading,
    companies,
    companyDetail,
    orders,
    orderDetail,
    trackingInfo,
    pagination,
    orderPagination,
    getLogisticsCompanyList,
    getLogisticsCompanyDetail,
    createLogisticsCompany,
    updateLogisticsCompany,
    deleteLogisticsCompany,
    getLogisticsOrderList,
    getLogisticsOrderDetail,
    createLogisticsOrder,
    updateLogisticsOrder,
    deleteLogisticsOrder,
    trackLogistics,
    printLogisticsOrder,
    setCompanyPagination,
    setOrderPagination,
    getAllLogisticsCompanies
  };
}); 